<template>
  <div id="edit">
    <div class="container" v-show="edittype == 'item'">
      <h1>编辑代办</h1>
      <input type="text" v-model="itemname" />
      <br />
      <button @click="sureedit">确定</button>
      <button @click="calc">取消</button>
    </div>

    <div class="container" v-show="edittype == 'user'">
      <h1>编辑用户</h1>
      <input type="text" v-model="username" />
      <input type="password" placeholder="请输入旧密码" v-model="oldpwd" />
      <input type="password" placeholder="请输入新密码" v-model="newpwd" />
      <br />
      <button @click="edituser">确定</button>
      <button @click="calc">取消</button>
    </div>
  </div>
</template>

<script>
export default {
  props: ['id', 'item', 'edittype'],
  data() {
    return {
      itemname: '',
      username: this.$store.state.user.name,
      oldpwd: '',
      newpwd: '',
    };
  },
  methods: {
    calc() {
      this.$emit('calitem');
    },
    async sureedit() {
      let res = await this.axios.get(`/item/update/${this.id}`, {
        params: { item: this.itemname },
      });
      if (res.data.status == 200) {
        let now = new Date();
        let datetime = `${now.getFullYear()}-${
          now.getMonth() + 1
        }-${now.getDate()}`;
        let res = await this.axios.get('/item/search', {
          params: { key: '', datetime },
        });
        let itemlist = res.data.data;
        this.$store.commit('GetItemList', {
          y: itemlist.y.items,
          n: itemlist.n.items,
        });

        this.$emit('calitem');
      }
    },
    async edituser() {
      let res = await this.axios.post('/user/edituser', {
        name: this.username,
        oldpwd: this.oldpwd,
        newpwd: this.newpwd,
      });
      if (res.data.msg == '修改成功') {
        this.$set(this.$store.state.user, 'name', this.username);
        this.oldpwd = '';
        this.newpwd = '';
        alert('修改成功');
        this.calc();
      }
    },
  },
  watch: {
    item(after, before) {
      this.itemname = after;
    },
    '$store.state.user.name'(after, before) {
      this.username = after;
    },
  },
};
</script>

<style scoped>
.container {
  width: 300px;
  padding: 30px 20px;
  background-color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}
h1 {
  font-size: 28px;
}
input {
  background: none;
  border: none;
  border-bottom: 1px solid;
  outline: none;
  font-size: 15px;
  padding: 10px 0 5px 0;
  margin-bottom: 10px;
}
button {
  width: 60px;
  height: 30px;
  margin: 20px 20px 0 20px;
  border: 1px solid#808080;
  background-color: white;
  cursor: pointer;
}
button:hover {
  background-color: #808080;
  color: white;
}
</style>
